package com.mazaiting.mybatisplus.sensitive.provider;

import com.mazaiting.mybatisplus.sensitive.ISensitive;
import com.mazaiting.mybatisplus.sensitive.FiledSensitive;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取脱敏器集合
 *
 * @author danghailiang
 */
public class SensitiveProvider {
    /**
     * 存放处理器
     */
    private static final ConcurrentHashMap<FiledSensitive, ISensitive> CACHE = new ConcurrentHashMap<>();

    /**
     * 通过注解获取加密器对象
     * @param filedSensitive 脱敏注解
     * @param globalDefaultSensitive 加敏器
     * @return  返回加密器
     */
    public static ISensitive get(FiledSensitive filedSensitive, Class<? extends ISensitive> globalDefaultSensitive) {
        // 查找脱敏器并返回啊
        return CACHE.computeIfAbsent(filedSensitive, ignored -> {
            try {
                // 判断specifiedEncryptor 是IEncryptor的实现类，不是则返回它本身
                Class<? extends ISensitive> specifiedEncryptor = filedSensitive.sensitive();
                // 返回加密器构造对象
                Class<? extends ISensitive> sensitive = specifiedEncryptor == ISensitive.class ? globalDefaultSensitive : specifiedEncryptor;
                return sensitive.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
}
